<?php

namespace App\Models\User;

use App\Models\BaseModel;

class Follow extends BaseModel
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'follow_id',
        'status',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'created_at',
        'updated_at',
    ];

    protected $table = 'follow';
    protected $dateFormat = 'U';

    /**
     * 关联follow
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function follow(){
        return $this->hasOne('App\Models\User\User', 'user_id', 'follow_id');
    }

    public function follower(){
        return $this->hasOne('App\Models\User\User', 'user_id', 'user_id');
    }

    /**
     * 关注列表
     * @param $user_id
     * @param $page
     * @param $size
     * @return mixed
     */
    public function followList($user_id, $page, $size){
        $data = [];
        $data['list'] = $this->select('follow.*')
            ->rightJoin('users',function($join) {
                $join->on('follow.follow_id', '=', 'users.user_id')->where('users.status', 1);
            })
            ->where('follow.user_id', $user_id)
            ->where('follow.status', 1)
            ->withOnly('follow', ['user_id', 'nickname', 'cover', 'vip_level'])
            ->forPage($page, $size+1)
            ->get()
            ->toArray();
        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;
        return $this->after($data);
    }

    /**
     * 粉丝列表
     * @param $follow_id
     * @param $page
     * @param $size
     * @return mixed
     */
    public function followerList($follow_id, $page, $size){
        $data = [];
        $data['list'] = $this->selectRaw('follow.*, if(f.status, 1, 0) as is_followed')
            ->where('follow.follow_id', $follow_id)
            ->where('follow.status', 1)
            ->leftJoin('follow as f', function($join) use($follow_id){
                $join->on('f.follow_id', 'follow.user_id')->where('f.user_id', $follow_id);
            })
            ->rightJoin('users',function($join) {
                $join->on('follow.follow_id', '=', 'users.user_id')->where('users.status', 1);
            })
            ->withOnly('follower', ['user_id', 'nickname', 'cover', 'vip_level'])
            ->forPage($page, $size+1)
            ->get()
            ->toArray();
        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;
        return $this->after($data);
    }
}
